package locks.dead.resources;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 带有时间的限制加锁
 */
public class Limit {

    ReentrantLock lock =new ReentrantLock();

    public boolean trySendOnShareLine(String message, long timeout, TimeUnit unit) throws InterruptedException {
        long nanosToLock = unit.toNanos(timeout)-estimetedNamosToSend(message);



        if(!lock.tryLock(nanosToLock,TimeUnit.NANOSECONDS)){
            return false;
        }
        try {
            return trySendOnShareLine(message);
        }finally {
            lock.unlock();
        }
    }

    /**
     * 发送
     * @param message
     * @return
     */
    private boolean trySendOnShareLine(String message) {

        return false;
    }

    /**
     * 估计要发送多长时间
     * @param message
     * @return
     */
    private long estimetedNamosToSend(String message) {

        return 0;
    }


    /**
     * 中断操作
     * @param message
     * @return
     * @throws InterruptedException
     */
    public boolean sendOnSharedLine(String message)
            throws InterruptedException {
        lock.lockInterruptibly();
        try {
            return cancellableSendOnSharedLine(message);
        } finally {
            lock.unlock();
        }
    }
    private boolean cancellableSendOnSharedLine(String message) throws InterruptedException {
        /* send something */
        return true;
    }

}
